﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Text;
using OneShoppingBLL;
using OneShoppingDAL;
using OneShoppingModel;
using OneShoppingUtility;
/// <summary>
///Global 的摘要说明
/// </summary>
 
 
namespace Global
{
    public class Global : System.Web.HttpApplication
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        private System.Timers.Timer myTimer;
        public Global()
        {
            InitializeComponent();
        }    
         
        //程序启动后定时执行脚本
        protected void Application_Start(Object sender, EventArgs e)
        {
            myTimer = new System.Timers.Timer(1000);
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimerSql);
            myTimer.Interval = 1000;
            myTimer.Enabled = true;
        }
  
        protected void Session_Start(Object sender, EventArgs e)
        {
            
        }
 
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
 
        }
 
        protected void Application_EndRequest(Object sender, EventArgs e)
        {
 
        }
 
        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
 
        }
 
        protected void Application_Error(Object sender, EventArgs e)
        {
            // 在出现未处理的错误时运行的代码 
            Exception ex = Server.GetLastError().GetBaseException();
            StringBuilder str = new StringBuilder();
            str.Append("\r\n" + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
            str.Append("\r\n.客户信息：");
            string ip = "";
            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
            {
                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            }
            else
            {
                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            str.Append("\r\n\tIp:" + ip);
            str.Append("\r\n\t请求地址：" + Request.UrlReferrer);
            str.Append("\r\n\t浏览器:" + Request.Browser.Browser.ToString());
            str.Append("\r\n\t浏览器版本:" + Request.Browser.MajorVersion.ToString());
            str.Append("\r\n\t操作系统:" + Request.Browser.Platform.ToString());
            str.Append("\r\n.错误信息：");
            str.Append("\r\n\t页面：" + Request.Url.ToString());
            str.Append("\r\n\t错误信息：" + ex.Message);
            str.Append("\r\n\t错误源：" + ex.Source);
            str.Append("\r\n\t异常方法：" + ex.TargetSite);
            str.Append("\r\n\t堆栈信息：" + ex.StackTrace);
            str.Append("\r\n--------------------------------------------------------------------------------------------------");
            //创建路径 
            string upLoadPath = Server.MapPath("~/log/");
            if (!System.IO.Directory.Exists(upLoadPath))
            {
                System.IO.Directory.CreateDirectory(upLoadPath);
            }
            //创建文件 写入错误 
            System.IO.File.AppendAllText(upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", str.ToString(), System.Text.Encoding.UTF8);
            //处理完及时清理异常 
            Server.ClearError();
            //跳转至出错页面 
            if (Request.UrlReferrer.ToString().IndexOf("/Backstage/") == -1)
            {
                Response.Write(null);//前端请求,服务器出错.
            }
            else
            {
                Response.Write(@"{<script>window.parent.errorPage();</script>}");
            }
            
        }
 
        protected void Session_End(Object sender, EventArgs e)
        {
            
        }
 
        protected void Application_End(Object sender, EventArgs e)
        {
            myTimer.Stop();
        }
             
        #region Web Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {    
            this.components = new System.ComponentModel.Container();
        }
        #endregion

        //定时检测活动状态
        private static void TimerSql(object source, System.Timers.ElapsedEventArgs e)
        {
            //0待审核1审核通过2审核没通过3活动正在进行4活动结束5活动失败6成功
            var listactivity = ActivityBLL.GetInstance().GetList(r => r.Status != 4 && r.Status != 6 && r.Status != 5);
            foreach(var activity in listactivity)
            {
                DateTime nowtime = DateTime.Now;
                if(activity.Status==3)
                {
                    if(nowtime.CompareTo(activity.EndTime)>0)
                    {
                        activity.Status = 5;
                        ActivityBLL.GetInstance().Update(activity);
                        var purchasing = PurchasingListBLL.GetInstance().GetList(r => r.ListId == activity.ListId);
                        foreach(var p in purchasing)
                        {
                            p.BuyStatus = 3;
                            PurchasingListBLL.GetInstance().Update(p);
                        }
                    }
                }
                else if(activity.Status==1)
                {
                    if (nowtime.CompareTo(activity.StartTime) > 0)
                    {
                        activity.Status = 3;
                        ActivityBLL.GetInstance().Update(activity);
                    }
                }
                else
                {
                    if(nowtime.CompareTo(activity.StartTime)>0)
                    {
                        activity.Status = 5;
                        ActivityBLL.GetInstance().Update(activity);
                    }
                }
            }
        }
    }
 
}